package nku.csc360;


/*Raj Kiran Akula
 *CSC 360
 *Homework 2
 *09/23/2009
 */


import java.io.*;

public class StockTest {
	public static void main(String[] args) throws FileNotFoundException, IOException {
		//Read Previous File
		Stock[] stocks = readPrevClosingPrices();
		
		//Called the sorting function so binarysearch can be used in the readTransaction method
		sortBySymbol(stocks);
		
		//Changed the return type of readTransaction so stocks contains new stocks added
		stocks = readTransactions("transactions.txt", stocks);
		
		//Print Stocks
		outputStocks("summary.txt", stocks);
	}
	
	//This following method is not changed
	public static Stock[] readPrevClosingPrices() throws FileNotFoundException, IOException {
		// Reads from an input file the previous closing prices of a set of stocks.  
		// Stores the information in the stocks array.
		// Returns the number of stocks that were read.
		FileReader fileReader = new FileReader("previous.txt");
		BufferedReader inFile = new BufferedReader(fileReader);
	
		// First count the number of stocks by reading through the file.
		int numStocks = 0;
		while (true) {
			String symbol = inFile.readLine(); // stock symbol
			if (symbol == null || symbol.equals(""))
				break;	
			inFile.readLine(); // stock name
			inFile.readLine(); // previous closing price
			inFile.readLine(); // blank line
			numStocks++;
		}
		inFile.close();

		fileReader = new FileReader("previous.txt");
		inFile = new BufferedReader(fileReader);		
		
		// Now allocate the array and read the stocks into it.
		Stock[] stocks = new Stock[numStocks];
		for (int i = 0; i < stocks.length; i++)	{
			String symbol = inFile.readLine();
			String name = inFile.readLine();
			double prevClosingPrice = Double.parseDouble(inFile.readLine());
			stocks[i] = new Stock(symbol, name, prevClosingPrice);
			inFile.readLine();
		}
		inFile.close();
		return stocks;
	}

	//This method is changed!!!!!!!!!
	public static Stock[] readTransactions(String fileName, Stock[] stocks) throws FileNotFoundException, IOException {
	// Reads in from an input file a set of stock transactions,
	// specified by stock symbol, number of shares, and sale price.
	// Transactions are separated by a single blank line.
	// Updates the relevant stocks.

		FileReader fileReader = new FileReader(fileName);
		BufferedReader inFile = new BufferedReader(fileReader);
		
		while (true) {
			String symbol = inFile.readLine();
			if (symbol == null || symbol.equals("")){
				break;	
			}
			String strNumShares = inFile.readLine();
			int numShares = Integer.parseInt(strNumShares);
			String strPrice = inFile.readLine();
			double price = Double.parseDouble(strPrice);
			inFile.readLine();
			
			//Changed from linear search to binary search so we can add new stocks
			int index = binarySearchSymbol(symbol, stocks);
			
			//Here check if there is a new stock if there is add the stock to our 
			//Data collection.
			if (index < 0){
				Stock stock = new Stock(symbol, "---", Double.NaN);
				stock.transaction(numShares, price);
				stocks = insertStock(stock, stocks, -(index + 1));
			}
			else
				stocks[index].transaction(numShares, price);
			}
		inFile.close();
		return stocks;		
	}

	public static void outputStocks(String fileName, Stock[] stocks) throws IOException {
	// Writes information on the stocks to an output file.

		PrintWriter outFile = new PrintWriter(fileName);

		outFile.println(Stock.headerString());
		for (int i = 0; i < stocks.length; i++)
			outFile.println(stocks[i]);		
		outFile.close();
	}
	
	public static int linearSearchSymbol(String keySymbol, Stock[] stocks) {
	// Searches for keySymbol in the array.
	// Returns the index at which the key value is found.
	// If the key value is not found, then the method returns -1.

		for (int i = 0; i < stocks.length; i++) 
			if (keySymbol.equals(stocks[i].getSymbol()))
				return i;	

		return -1;		
	}
	
	//Part 1 of Homework 2
	//Method used to sort stocks take a parameter object Stock 
	//array to compare and switch around the stocks that are 
	//smaller and bigger.
	
	public static void sortBySymbol(Stock[] stocks){
		
		//This is the selection sort just took the sort from java book
		//and adapted it to this code.
		
		for(int i = stocks.length -1; i >= 1; i--){
			Stock currentMax = stocks[0];
			int currentMaxIndex = 0;
			for (int j = 1; j <= i; j++){
				if(currentMax.getSymbol().compareToIgnoreCase(stocks[j].getSymbol()) < 0){
					currentMax = stocks[j];
					currentMaxIndex = j;
				}
			}
		
			if(currentMaxIndex != i){
				stocks[currentMaxIndex] = stocks[i];
				stocks[i] = currentMax;
			}
		}
	
	}

	//Homework Part 2 of assignment
	public static int binarySearchSymbol(String keySymbol, Stock[] stocks){
		//Just took the binary search from java textbook and adapted it 
		//to this problem
		
		int low = 0;
		int high = stocks.length-1;
		while(high >= low){
			int mid = (low+high)/2;
			if(keySymbol.compareToIgnoreCase(stocks[mid].getSymbol()) < 0){
				high = mid - 1;
			}
			else if(keySymbol.compareToIgnoreCase(stocks[mid].getSymbol())==0){
				return mid;
			}
			else
				low = mid + 1;
		}
			return (-low-1);
		
		
		
	}
	
	public static Stock[] insertStock(Stock stock, Stock[] stocks, int insertionPoint){
		
		//Declaring new stock array to return
		Stock[] stocks1 = new Stock[(stocks.length + 1)];
		
		//Temporary value for stock at insertion point to move to next point
		//Initially it is value of stock to insert
		Stock temp = stock;
		
		//Temporary value to run through the loop
		int a = 0; 
		
		while(a <= stocks.length){
			
			//Condition for when you don't have to insert anything
			//yet since the place to insert isn't found yet
			if (a < insertionPoint){
				stocks1[a] = stocks[a];
				a++;
			}
			//Inserting where the newly to be added stock is supposed
			//to be.
			else if (a == insertionPoint){
				stocks1[a] = temp;
				a++;
			}
			//Then filling up the remaining stock!!!!!!!
			else{
				stocks1[a] = stocks[a-1];
				++a;
			}
		}
		return(stocks1);
	}
		
}
